<?php
error_reporting ( 0 );
session_start ();
set_time_limit(0);
define ( 'YLSNS_INSTALL', TRUE );
define ( 'YLSNS', str_replace ( '\\', '/', substr ( dirname ( __FILE__ ), 0, - 7 ) ) );
$_YLVERSION = '1.0';
include 'install_function.php';
include 'install_lang.php';

$timestamp = time ();
$ip = getip ();
$installfile = 'ylsns.sql';
$OceanSNS_config_file = 'dbutil.php';
$ucconfigfile = 'config_ocean.php';
// 判断是否安装过
header ( 'Content-Type: text/html; charset=utf-8' );
if (file_exists ( 'install.lock' )) {
	exit ( $i_message ['install_lock'] );
}
if (! is_readable ( $installfile )) {
	exit ( $i_message ['install_dbFile_error'] );
}
$quit = false;
$msg = $alert = $link = $sql = $allownext = '';

$PHP_SELF = addslashes ( htmlspecialchars ( $_SERVER ['PHP_SELF'] ? $_SERVER ['PHP_SELF'] : $_SERVER ['SCRIPT_NAME'] ) );
set_magic_quotes_runtime ( 0 );
if (! get_magic_quotes_gpc ()) {
	addS ( $_POST );
	addS ( $_GET );
}
@extract ( $_POST );
@extract ( $_GET );
?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
	<meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible" />
	<title><?php echo $i_message['install_wizard']; ?></title>
	<link href="css/install.css" rel="stylesheet" type="text/css" />
</head>
<body>
	<div id='content'  class="step step1">
		<div id='pageheader'  class="header">
			<h1><img src="css/img/install/logo.png" alt="logo" /></h1>
			<p class="ver">Version <?php echo $_YLVERSION; ?></p>
		</div>
<?php
if (! $v) {
	?>
<div class="content">
	<div  class="hd">
		<?php echo $i_message['install_title'];?>
		<?php echo $i_message['install_warning'];?>
	</div>
	<div class="summary">
		<?php echo $i_message['install_intro'];?>
	</div>
	<div class="actions">
		<a href="install.php?v=1" class="btn"><?php echo $i_message['install_start'];?></a>
	</div>
</div>
<?php
} elseif ($v == '1') {
	?>
<div class="content">
	<div class="hd">
		<?php echo $i_message['install_title'];?>
	</div>
	<form action="install.php?v=2"  method="post">
		<div class="agree">
			<h3 class="agree-title"><?php echo $i_message['install_license_title'];?></h3>
			<div class="agree-content">
				<?php echo $i_message['install_license'];?>
			</div>
		</div>
		<div class="agree-ft"><label><input type="checkbox"  name="agree" value="1" onClick="if(this.checked==true){this.form.next.disabled=''}else{this.form.next.disabled='true'}"
			checked="checked" /><?php echo $i_message['install_agree'];?></label>
		</div>
		<div class="actions">
			<input type="submit"  name="next" class="btn" value="<?php echo $i_message['install_next'];?>" />
		</div>
	</form>
</div>
<?php
} elseif ($v == '2') {
	if ($agree == 'no') {
		echo '<script>alert(' . $i_message ['install_disagree_license'] . ');history.go(-1)</script>';
	}
	$dirarray = array (
			'install'
	);
	$writeable = array ();
	foreach ( $dirarray as $key => $dir ) {
		if (writable ( $dir )) {
			$writeable [$key] = $dir . result ( 1, 0 );
		} else {
			$writeable [$key] = $dir . result ( 0, 0 );
			$quit = TRUE;
		}
	}
	?>
<div class="content">
	<div class="hd">
		<?php echo $i_message['install_title'];?>
	</div>
	<div class="block">
		<h3 class="ti"><?php echo $i_message['install_env'];?></h3>
		<dl class="info">
			<dt><?php echo $i_message['php_os'];?></dt>
			<dd><?php echo PHP_OS;result(1, 1);?></dd>
			<dt><?php echo $i_message['php_version'];?></dt>
			<dd><?php
					echo PHP_VERSION;
					if (PHP_VERSION < '5.1.2') {
						result ( 0, 1 );
						$quit = TRUE;
					} else {
						result ( 1, 1 );
					}
					?></dd>
			<dt><?php echo $i_message['file_upload'];?></dt>
			<dd><?php
					if (@ini_get ( 'file_uploads' )) {
						echo $i_message ['support'], '/', @ini_get ( 'upload_max_filesize' );
					} else {
						echo '<span class="fail">' . $i_message ['unsupport'] . '</span>';
					}
					result ( 1, 1 );
					?></dd>
			<dt><?php echo $i_message['php_extention'];?></dt>
			<dd>
				<?php
	if (extension_loaded ( 'mysql' )) {
		echo 'mysql:' . $i_message ['support'];
		result ( 1, 1 );
	} else {
		echo '<span class="fail">' . $i_message ['php_extention_unload_mysql'] . '</span>';
		result ( 0, 1 );
		$quit = TRUE;
	}
	?><br />
				<?php
	if (extension_loaded ( 'gd' )) {
		echo 'gd:' . $i_message ['support'];
		result ( 1, 1 );
	} else {
		echo '<span class="fail">' . $i_message ['php_extention_unload_gd'] . '</span>';
		result ( 0, 1 );
		$quit = TRUE;
	}
	?><br />
				<?php
	if (extension_loaded ( 'curl' )) {
		echo 'curl:' . $i_message ['support'];
		result ( 1, 1 );
	} else {
		echo '<span class="fail">' . $i_message ['php_extention_unload_curl'] . '</span>';
		result ( 0, 1 );
		$quit = TRUE;
	}
	?><br />
				<?php
	if (extension_loaded ( 'mbstring' )) {
		echo 'mbstring:' . $i_message ['support'];
		result ( 1, 1 );
	} else {
		echo '<span class="fail">' . $i_message ['php_extention_unload_mbstring'] . '</span>';
		result ( 0, 1 );
		$quit = TRUE;
	}
	?>
			</dd>
			<dt><?php echo $i_message['mysql'];?></dt>
			<dd><?php
	if (function_exists ( 'mysql_connect' )) {
		echo $i_message ['support'];
		result ( 1, 1 );
	} else {
		echo '<span class="fail">' . $i_message ['mysql_unsupport'] . '</span>';
		result ( 0, 1 );
		$quit = TRUE;
	}
	?></dd>
		</dl>
	</div>
	<!-- 注意：最后一个块添加 block-last -->
	<div class="block block-last">
		<h3 class="ti"><?php echo $i_message['dirmod'];?></h3>
		<dl class="info">
			<dt><?php
	foreach ( $writeable as $value ) {
		echo '<p>' . $value . '</p>';
	}
	if (is_writable ( YLSNS . $OceanSNS_config_file )) {
		echo '<p>' . $OceanSNS_config_file . result ( 1, 0 ) . '</p>';
	} else {
		echo '<p>' . $OceanSNS_config_file . result ( 0, 0 ) . '</p>';
		$quit = TRUE;
	}
	?></dt>
			<dd><!-- <span class='red'><?php echo $i_message['install_dirmod'];?></span> --></dd>
		</dl>
	</div>
	<div class="actions">
		<a href="install.php?v=3" class="btn"><?php echo $i_message['install_next'];?></a>
	</div>
</div>
<?php
} elseif ($v == '3') {
	?>
		<div class="content">
			<div class="hd">
				<h2 class="ti"><?php echo $i_message['install_title'];?></h2>
			</div>
			<form method="post" action="install.php?v=4" id="install" onSubmit="return check(this);">
			<div class="block">
				<h3 class="ti"><?php echo $i_message['install_mysql'];?></h3>
					<div class="kv">
						<div class="kv-label">
							<label for=""><?php echo $i_message['install_mysql_host'];?></label>
							<p class="tip"><?php echo $i_message['install_mysql_host_intro'];?></p>
						</div>
						<input type="text" name="db_host" value="localhost" size="40" class='text' />
						<p class="kv-error"></p>
					</div>
					<div class="kv">
						<div class="kv-label">
							<label for=""><?php echo $i_message['install_mysql_username'];?></label>
						</div>
						<input type="text" name="db_username" value="root" size="40"
							class='text' />
						<p class="kv-error"></p>
					</div>
					<div class="kv">
						<div class="kv-label">
							<label for=""><?php echo $i_message['install_mysql_password'];?></label>
						</div>
						<input type="password" name="db_password" value="" size="40"
							class='text' />
						<p class="kv-error"></p>
					</div>
					<div class="kv">
						<div class="kv-label">
							<label for=""><?php echo $i_message['install_mysql_name'];?></label>
						</div>
						<input type="text" name="db_name" value="OceanX" size="40"
							class='text' />
						<p class="kv-error"></p>
					</div>
					<div class="kv">
						<div class="kv-label">
							<label for=""><?php echo $i_message['install_mysql_prefix'];?></label>
							<p class="tip"><?php echo $i_message['install_mysql_prefix_intro'];?></p>
						</div>
						<input type="text" name="db_prefix" value="yl_" size="40"
							class='text' />
						<p class="kv-error"></p>
					</div>
					<div class="kv">
						<div class="kv-label">
							<label for=""><?php echo $i_message['site_url'];?></label>
							<p><?php echo $i_message['site_url_intro'];?></p>
						</div>
						<input type="text" name="site_url"
							value="<?php echo "http://".$_SERVER['HTTP_HOST'].rtrim(str_replace('\\', '/', dirname(dirname($_SERVER['SCRIPT_NAME']))),'/');?>"
							size="40" class='text' />
						<p class="kv-error"></p>
					</div>
			</div>
            <div class="block">
                <h3 class="ti"><?php echo $i_message['cmsstyle'];?></h3>
                <div class="kv">
                    <select name="cmsstyle" id="cmsstyle">
                        <option value=""><?php echo $i_message['setting_template_style'];?></option>
                    <?php
                        $templatelist = getTemplateName();
                        foreach ($templatelist as $k => $v) {
                    ?>
                            <option value="<?php echo $k;?>"><?php echo $v;?></option>
                    <?php
                        }
                    ?>
                    </select>
                </div>
            </div>
			<!-- 注意：最后一个块添加 block-last -->
			<div class="block block-last">
				<h3 class="ti"><?php echo $i_message['founder'];?></h3>
					<div class="kv">
						<div class="kv-label">
							<label for=""><?php echo $i_message['auto_increment'];?></label>
						</div>
						<input type="text" name="first_user_id" value="1" size="40" class='text' />
						<p class="kv-error"></p>
					</div>
					<div class="kv">
						<div class="kv-label">
							<label for=""><?php echo $i_message['install_founder_email'];?></label>
						</div>
						<input type="text" name="email" value="admin@admin.com" size="40" class='text' />
						<p class="kv-error"></p>
					</div>
					<div class="kv">
						<div class="kv-label">
							<label for=""><?php echo $i_message['install_founder_password'];?></label>
						</div>
						<input type="text" name="password" value="" size="40" class='text' />
						<p class="kv-error"></p>
					</div>
					<div class="kv">
						<div class="kv-label">
							<label for=""><?php echo $i_message['install_founder_rpassword'];?></label>
						</div>
						<input type="text" name="rpassword" value="" size="40" class='text' />
						<p class="kv-error"></p>
					</div>
			</div>
			<div class="actions">
				<a href="javascript:history.go(-1);" class="btn btn-prev"><?php echo $i_message['install_prev'];?></a>
				<input type="submit" class="btn" value="<?php echo $i_message['install_next'];?>" />
			</div>
			</form>
		</div>
<script type="text/javascript" language="javascript">
function check(obj) {
	if (!obj.db_host.value) {
		alert('<?php echo $i_message['install_mysql_host_empty'];?>');
		obj.db_host.focus();
		return false;
	} else if (!obj.db_username.value) {
		alert('<?php echo $i_message['install_mysql_username_empty'];?>');
		obj.db_username.focus();
		return false;
	} else if (!obj.db_name.value) {
		alert('<?php echo $i_message['install_mysql_name_empty'];?>');
		obj.db_name.focus();
		return false;
	} else if (obj.password.value.length < 6) {
		alert('<?php echo $i_message['install_founder_password_length'];?>');
		obj.password.focus();
		return false;
	} else if (obj.password.value != obj.rpassword.value) {
		alert('<?php echo $i_message['install_founder_rpassword_error'];?>');
		obj.rpassword.focus();
		return false;
	} else if (!obj.email.value) {
		alert('<?php echo $i_message['install_founder_email_empty'];?>');
		obj.email.focus();
		return false;
	}
	return true;
}
</script>
<?php
} elseif ($v == '4') {
	if (empty ( $db_host ) || empty ( $db_username ) || empty ( $db_name ) || empty ( $db_prefix )) {
		$msg .= '<p>' . $i_message ['mysql_invalid_configure'] . '<p>';
		$quit = TRUE;
	} elseif (! @mysql_connect ( $db_host, $db_username, $db_password )) {
		$msg .= '<p>' . mysql_error () . '</p>';
		$quit = TRUE;
	}
	if (strstr ( $db_prefix, '.' )) {
		$msg .= '<p>' . $i_message ['mysql_invalid_prefix'] . '</p>';
		$quit = TRUE;
	}
	if (strlen ( $password ) < 6) {
		$msg .= '<p>' . $i_message ['founder_invalid_password'] . '</p>';
		$quit = TRUE;
	} elseif ($password != $rpassword) {
		$msg .= '<p>' . $i_message ['founder_invalid_rpassword'] . '</p>';
		$quit = TRUE;
	} elseif (! preg_match ( '/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,3}$/i', $email )) {
		$msg .= '<p>' . $i_message ['founder_invalid_email'] . '</p>';
		$quit = TRUE;
	} else {
		$forbiddencharacter = array ("\\","&"," ","'","\"","/","*",",","<",">","\r","\t","\n","#","$","(",")","%","@","+","?",";","^");
		foreach ( $forbiddencharacter as $value ) {
			if (strpos ( $username, $value ) !== FALSE) {
				$msg .= '<p>' . $i_message ['forbidden_character'] . '</p>';
				$quit = TRUE;
				break;
			}
		}
	}
	?>
	<div class="content">
			<div class="hd">
				<h2 class="ti"><?php echo $i_message['install_title'];?></h2>
			</div>
			<div class="bd">
<?php
	if ($quit) {
		$allownext = 'disabled="disabled"';
?>
		<div class="error"><?php echo $i_message['error'];?></div>
<?php
		echo $msg;
	} else {
		$config_file_content = array ();
		$config_file_content ['db_host'] = $db_host;
		$config_file_content ['db_name'] = $db_name;
		$config_file_content ['db_username'] = $db_username;
		$config_file_content ['db_password'] = $db_password;
		$config_file_content ['db_prefix'] = $db_prefix;
		$config_file_content ['db_pconnect'] = 0;
		$config_file_content ['db_charset'] = 'utf8';
		$config_file_content ['dbType'] = 'MySQL';

		$default_manager_account = array ();
		$default_manager_account ['email'] = $email;
		$default_manager_account ['password'] = md5 ( $password );

		$_SESSION ['config_file_content'] = $config_file_content;
		$_SESSION ['default_manager_account'] = $default_manager_account;
		$_SESSION ['first_user_id'] = $first_user_id;
		$_SESSION ['site_url'] = $site_url;
        $_SESSION ['cmsstyle'] = $cmsstyle;
	}
	?>
		<br >
		<p><?php echo $i_message['install_founder_name'], ': ', $email?></p>
		<p><?php echo $i_message['install_founder_password'], ': ', $password;?></p>
<?php
	// 写配置文件
	$fp = fopen ( YLSNS . $OceanSNS_config_file, 'wb' );
	$configfilecontent = <<<EOT
<?php
//if (!defined('SITE_PATH')) exit();
\$db = array(
	// 数据库常用配置
	'DB_TYPE'			=>	'mysql',			// 数据库类型
	'DB_HOST'			=>	'$db_host',			// 数据库服务器地址
	'DB_NAME'			=>	'$db_name',			// 数据库名
	'DB_USER'			=>	'$db_username',		// 数据库用户名
	'DB_PWD'			=>	'$db_password',		// 数据库密码
	'DB_PORT'			=>	3306,				// 数据库端口
	'DB_PREFIX'			=>	'$db_prefix',		// 数据库表前缀（因为漫游的原因，数据库表前缀必须写在本文件）
	'DB_CHARSET'		=>	'utf8',				// 数据库编码
	'DB_FIELDTYPE_CHECK'    => false,       // 是否进行字段类型检查
	'DB_FIELDS_CACHE'	=>	true,				// 启用字段缓存

	'DB_DEPLOY_TYPE'        => 0, 				// 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
	'DB_RW_SEPARATE'        => false,       	// 数据库读写是否分离 主从式有效
	'DB_MASTER_NUM'         => 1,				// 读写分离后 主服务器数量
	'DB_SLAVE_NO'           => '', 				// 指定从服务器序号
	'DB_SQL_BUILD_CACHE'    => false, 			// 数据库查询的SQL创建缓存
	'DB_SQL_BUILD_QUEUE'    => 'file',   		// SQL缓存队列的缓存方式 支持 file xcache和apc
	'DB_SQL_BUILD_LENGTH'   => 20, 				// SQL缓存的队列长度
	'DB_SQL_LOG'            => false, 			// SQL执行日志记录

);
\$oceanConfig = include "config_ocean.php";
return array_merge ( \$oceanConfig, \$db );
EOT;
	$configfilecontent = str_replace ( 'SECURE_TEST', 'SECURE' . rand ( 10000, 20000 ), $configfilecontent );
	
	$result_1 = fwrite ( $fp, trim ( $configfilecontent ) );
	@fclose ( $fp );

	$fps = fopen ( YLSNS . $ucconfigfile, 'wb' );
	$ucconfigcontent = <<<EOT
<?php
return array(
	'DEFAULT_APPS'      	=> array('mobile', 'admin', 'home', 'weibo','api'),
	'DEFAULT_CHARSET' => 'utf-8',
	'DEFAULT_TIMEZONE' => 'PRC',
	'APP_FILE_CASE' => true, // 是否检查文件的大小写 对Windows平台有效
	'APP_PLUGIN_ON'         => true,
	'YL_KEY'		    => 'OCEANX',
	'YL_IP'				=> '',

	'USER_AUTH_ON' => true,
	'USER_AUTH_TYPE' => 1, // 默认认证类型 1 登录认证 2 实时认证
	'USER_AUTH_KEY' => 'authId', // 用户认证SESSION标记
	'ADMIN_AUTH_KEY' => 'super_administrator',
	'USER_AUTH_MODEL' => 'User', // 默认验证数据表模型
	'AUTH_PWD_ENCODER' => 'md5', // 用户认证密码加密方式
	'USER_AUTH_GATEWAY' => 'admin/Public/login', // 默认认证网关
	'NOT_AUTH_ADMIN' => array('1'), // 默认无需认证用户id
	'NOT_AUTH_MODULE' => 'Public', // 默认无需认证模块
	'REQUIRE_AUTH_MODULE' => '', // 默认需要认证模块
	'NOT_AUTH_ACTION' => '', // 默认无需认证操作
	'REQUIRE_AUTH_ACTION' => '', // 默认需要认证操作
	'GUEST_AUTH_ON' => false, // 是否开启游客授权访问
	'GUEST_AUTH_ID' => 0, // 游客的用户ID
	'DB_LIKE_FIELDS' => 'title|remark',
	'RBAC_ROLE_TABLE' => 'yl_role',
	'RBAC_USER_TABLE' => 'yl_role_user',
	'RBAC_ACCESS_TABLE' => 'yl_access',
	'RBAC_NODE_TABLE' => 'yl_node'
);
EOT;
	
	$result_2 = fwrite ( $fps, trim ( $ucconfigcontent ) );
	@fclose ( $fps );
	if ($result_1 && file_exists ( YLSNS . $OceanSNS_config_file )) {
		?>
	<p><?php echo $i_message['config_log_success']; ?></p>
<?php
	} else {
		?>
	<p><?php echo $i_message['config_read_failed']; $quit = TRUE;?></p>
<?php
	}
	?>
	</div>
	<div class="actions">
		<a href="javascript:history.go(-1);" class="btn btn-prev"><?php echo $i_message['install_prev'];?></a>
		<a href="<?php if(!$quit) echo "install.php?v=5";?>" class="btn" ><?php echo $i_message['install_next'];?></a>
	</div>
<?php
} elseif ($v == '5') {
	$db_config = $_SESSION ['config_file_content'];
	if (! $db_config ['db_host'] && ! $db_config ['db_name']) {
		$msg .= '<p>' . $i_message ['configure_read_failed'] . '</p>';
		$quit = TRUE;
	} else {
		mysql_connect ( $db_config ['db_host'], $db_config ['db_username'], $db_config ['db_password'] );
		$sqlv = mysql_get_server_info ();
		if ($sqlv < '4.1') {
			$msg .= '<p>' . $i_message ['mysql_version_402'] . '</p>';
			$quit = TRUE;
		} else {
			$db_charset = $db_config ['db_charset'];
			$db_charset = (strpos ( $db_charset, '-' ) === FALSE) ? $db_charset : str_replace ( '-', '', $db_charset );

			mysql_query ( " DROP DATABASE IF EXISTS `{$db_config['db_name']}`" );

			mysql_query ( " CREATE DATABASE `{$db_config['db_name']}` DEFAULT CHARACTER SET $db_charset " );

			if (mysql_errno ()) {
				$errormsg = mysql_error ();
				$msg .= '<p>' . ($errormsg ? $errormsg : $i_message ['database_errno']) . '</p>';
				$quit = TRUE;
			} else {
				mysql_select_db ( $db_config ['db_name'] );
			}
			// 判断是否有用同样的数据库前缀安装过
			$re = mysql_query ( "SELECT COUNT(1) FROM {$db_config['db_prefix']}user" );
			$link = @mysql_fetch_row ( $re );
			if (intval ( $link [0] ) > 0) {
				$YLSNS_rebuild = true;
				$msg .= '<p>' . $i_message ['YLSNS_rebuild'] . '</p>';
				$alert = ' onclick="return confirm(\'' . $i_message ['YLSNS_rebuild'] . '\');"';
			}
		}
	}
	if ($quit) {
		$allownext = 'disabled="disabled"';
		?>
<div class="error"><?php echo $i_message['error'];?></div>
<?php
		echo $msg;
	} else {
?>
<div class="content">
	<div class="hd">
		<h2 class="ti"><?php echo $i_message['install_title'];?></h2>
	</div>
	<div class="bd">
<?php if ($YLSNS_rebuild) { ?>
<p style="color: red; font-size: 16px;"><?php echo $i_message['YLSNS_rebuild'];?></p>
<?php } ?>
<p><?php echo $i_message['mysql_import_data'];?></p>
		</div>
<?php } ?>
	<div class="actions">
		<a href="javascript:history.go(-1);" class="btn btn-prev"><?php echo $i_message['install_prev'];?></a>
		<a href="<?php if(!$quit) echo "install.php?v=6";?>" class="btn"><?php echo $i_message['install_next'];?></a>
	</div>
<?php
} elseif ($v == '6') {
	$db_config = $_SESSION ['config_file_content'];
	mysql_connect ( $db_config ['db_host'], $db_config ['db_username'], $db_config ['db_password'] );
	if (mysql_get_server_info () > '5.0') {
		mysql_query ( "SET sql_mode = ''" );
	}
	$db_config ['db_charset'] = (strpos ( $db_config ['db_charset'], '-' ) === FALSE) ? $db_config ['db_charset'] : str_replace ( '-', '', $db_config ['db_charset'] );
	mysql_query ( "SET character_set_connection={$db_config['db_charset']}, character_set_results={$db_config['db_charset']}, character_set_client=binary" );
	mysql_select_db ( $db_config ['db_name'] );
	$tablenum = 0;

	$fp = fopen ( $installfile, 'rb' );
	$sql = fread ( $fp, filesize ( $installfile ) );
	fclose ( $fp );
	?>
<div class="content">
	<div class="hd">
		<h2 class="ti"><?php echo $i_message['install_title'];?></h2>
	</div>
	<div class="block">
		<h3 class="ti"><?php echo $i_message['install_success'];?></h3>
		<dl class="info">
			<dt><?php echo $i_message['import_processing'];?></dt>
			<dd>
			<div style="overflow-y: scroll; height: 100px; padding: 5px; border: 1px solid #ccc;">
<?php
	$db_charset = $db_config ['db_charset'];
	$db_prefix = $db_config ['db_prefix'];
    $sql = str_replace("\r", "\n", str_replace('`'.'yl_', '`'.$db_prefix, $sql));
	foreach ( explode ( ";\n", trim ( $sql ) ) as $query ) {
		$query = trim ( $query );
		if ($query) {
			if (substr ( $query, 0, 26 ) == 'CREATE TABLE IF NOT EXISTS') {
				$name = preg_replace ( "/CREATE TABLE ([A-Z ]*)`([a-z0-9_]+)` .*/is", "\\2", $query );
				echo '<p>' . $i_message ['create_table'] . ' ' . $name . ' ... <span class="ok">OK</span></p>';
				@mysql_query ( createtable ( $query, $db_charset ) );
				$tablenum ++;
			} else {
				@mysql_query ( $query );
			}
		}
	}

	$url = 'http://' . $_SERVER ['SERVER_NAME'];
	$kkk = authcode ( 'OCEANX', 'ENCODE', 'cs5H7Z2bbC9lfi6ift7DaDfQfH6r0U5M4C755l5K6908dD8Nahdz9U6YbX2E2J7Q' );
	$resultSql = "insert into {$db_prefix}applications(appid,name,url,authkey) values(1,'oceanx','$url','$kkk')";
	mysql_query ( $resultSql );

	$ss = "drop function if exists getChildLst; DELIMITER // ";
	$sqlss = <<<EOF
CREATE FUNCTION `getChildLst`(rootId smallint) RETURNS varchar(1000) CHARSET utf8
BEGIN
DECLARE sTemp VARCHAR(1000);
DECLARE sTempChd VARCHAR(1000);
SET sTemp = '$';
SET sTempChd =cast(rootId as CHAR);
WHILE sTempChd is not null DO
SET sTemp = concat(sTemp,',',sTempChd);
SELECT group_concat(id) INTO sTempChd FROM yl_node where FIND_IN_SET(pid,sTempChd)>0;
END WHILE;
RETURN sTemp;
END;
EOF;
	@mysql_query ( $ss );
	@mysql_query ( $sqlss );
	?>
</div>
</dd>
<dt><?php echo $i_message['create_founder'];?></dt>
	<dd>
<?php
	// 设置网站用户起始ID
	if (intval ( $_SESSION ['first_user_id'] ) > 0) {
		$admin_id = intval ( $_SESSION ['first_user_id'] );
		$sql0 = "ALTER TABLE `{$db_config['db_prefix']}user` AUTO_INCREMENT=" . $admin_id . ";";
		if (mysql_query ( $sql0 )) {
			echo '<p>' . $i_message ['set_auto_increment_success'] . '... <span class="ok">OK..' . $admin_id . '</span></p>';
		} else {
			echo '<p>' . $i_message ['set_auto_increment_error'] . '... <span class="fail">ERROR</span></p>';
			$admin_id = 1;
		}
	} else {
		$admin_id = 1;
	}

	// 添加管理员
	$siteFounder = $_SESSION ['default_manager_account'];

	$sql1 = "INSERT INTO `{$db_config['db_prefix']}user` (`uid`, `email`, `password`, `uname`, `sex`, `province`, `city`, `location`, `admin_level`, `commend`, `is_active`, `is_init`, `is_synchronizing`, `cTime`, `identity`, `score`,`myop_menu_num`,`api_key`,`domain`) VALUES (" . $admin_id . ", '" . $siteFounder ['email'] . "', '" . $siteFounder ['password'] . "', '管理员', '0', '0', '0', NULL, '1', NULL, '1', '1', '0', " . time () . ", '1', '0', '10', NULL, '');";
	if (mysql_query ( $sql1 )) {
		echo '<p>' . $i_message ['create_founderpower_success'] . '... <span class="ok">OK</span></p>';
	} else {
		echo '<p>' . $i_message ['create_founderpower_error'] . '... <span class="fail">ERROR</span></p>';
		$quit = true;
	}
	if (! $quit) {
        $cmsstyle = $_SESSION ['cmsstyle'];
		$sqlnode = "INSERT INTO `{$db_config['db_prefix']}node` (`id`, `name`, `title`, `status`, `remark`, `sort`, `pid`, `level`, `type`, `group_id`) VALUES
					(1, 'admin', NULL, 1, NULL, NULL, 0, 1, 0, 0)";
		mysql_query ( $sqlnode );
		$filename = '../apps/cms/Appinfo/install.sql';
		if(file_exists($filename)) {
			$res = executeSqlFile($filename);
			if(empty($res)) {
				$url = "http://".$_SERVER['HTTP_HOST'].rtrim(str_replace('\\', '/', dirname(dirname($_SERVER['SCRIPT_NAME']))),'/');
				$sqlapp = "INSERT INTO `{$db_config['db_prefix']}app` (`app_id`, `app_name`, `app_alias`, `description`, `version`, `status`, `category`, `release_date`, `last_update_date`, `host_type`, `app_entry`, `icon_url`, `large_icon_url`, `admin_entry`, `statistics_entry`, `homepage_url`, `sidebar_title`, `sidebar_entry`, `sidebar_icon_url`, `sidebar_support_submenu`, `sidebar_is_submenu_active`, `author_name`, `author_email`, `author_homepage_url`, `contributor_name`, `display_order`, `ctime`, `isalone`, `ishomeshow`) VALUES
				(11, 'cms', 'CMS', '内容管理系统', '1.1', 2, '工具', '2013-01-29', '2013-01-29', 0, 'Index/index', '".$url."/apps/cms/Appinfo/ico_app.png', '".$url."/apps/cms/Appinfo/ico_app_large.png', 'Admin/index', 'EventStatistics/statistics', '', '', '', '', 0, 0, '涌浪', 'service@yonglang.co', 'www.yonglang.co', 'M2', 11, 1374197725, 1, 0)";
				mysql_query($sqlapp);
                if (empty($cmsstyle)) {
                    $sqlCate = "INSERT INTO `{$db_config['db_prefix']}cms_category`(plistid,cname,catetemplate,arttemplate,createurl,catenaming,
							artnaming,create_uid,create_uname,update_uid,update_uname,inputtime,updatetime) values('0','首页','channel.html',
							'content.html','','channels-{cateid}.html','contents-{contentid}.html',".$admin_id.",'管理员',".$admin_id.",
							'管理员','".time()."','".time()."')";
                    mysql_query($sqlCate);
                    $id = mysql_insert_id();
                    $sqlUpdateCate = "UPDATE `{$db_config['db_prefix']}cms_category` SET siteid=".$id.",display_order=".$id." WHERE id=".$id;
                    mysql_query($sqlUpdateCate);
                    $sqlSite = "INSERT INTO `{$db_config['db_prefix']}cms_site`(siteid,name,domain,status) VALUES(".$id.",'产品官网',
							'".$url."','1')";
                    mysql_query($sqlSite);
                    $sqlTemplate = "INSERT INTO `{$db_config['db_prefix']}cms_templates`(siteid,template_type,template_name,create_name) VALUES(
								".$id.",'home','index.html','index.html'),(".$id.",'channels','channel.html',''),(".$id.",'contents','content.html','')";
                    mysql_query($sqlTemplate);
                    $getSiteTemplatePath = "SELECT dirname  FROM `{$db_config['db_prefix']}cms_site` WHERE siteid=".$id;
                    $result_template = mysql_query($getSiteTemplatePath);
                    $result_dirname = mysql_result($result_template,0);
                    $dirname = empty($result_dirname)?'':$result_dirname.'/';
                    $templatePath = YLSNS.$dirname.'templates/';
                    $arr = array('index.html','channel.html','content.html');
                    if (!file_exists($templatePath)) {
                        mk_dir($templatePath);
                    }
                    //创建空模版
                    foreach ($arr as $v) {
                        file_put_contents($templatePath.$v,'');
                    }
                    $map['channelTemplate'] = 'channel.html';
                    $map['contentTemplate'] = 'content.html';
                    $map['catenaming'] = 'channels-{cateid}.html';
                    $map['artnaming'] = 'contents-{contentid}.html';
                    $map['picSavePath'] = './data/cms/upload';
                    $map['createchannel'] = '0';
                    $map['createcontent'] = '0';
                    $arr1['site-'.$id] = $map;
                    if(is_array($arr1)){
                        $insert_sql .= "REPLACE INTO `{$db_config['db_prefix']}system_data` (`list`,`key`,`value`,`mtime`) VALUES ";
                        foreach($arr1 as $key=>$data){
                            $insert_sql	.= " ('cmsconfig','$key','".serialize($data)."','".date('Y-m-d H:i:s')."') ,";
                        }
                        $insert_sql	= rtrim($insert_sql,',');
                        //插入数据列表
                        mysql_query($insert_sql);
                    }
                } else {
                    readNodeXml('../Public/cms/template/'.$cmsstyle.'/sitedata/node.xml');
                    $siteid = readSiteXml('../Public/cms/template/'.$cmsstyle.'/sitedata/sitedata.xml');
                    addSystemConfig('../Public/cms/template/'.$cmsstyle.'/sitedata/sitedata.xml', $siteid);
                    readTemplateXml('../Public/cms/template/'.$cmsstyle.'/sitedata/template.xml');
                    readContentXml('../Public/cms/template/'.$cmsstyle.'/sitedata/content.xml');
                    readGroupXml('../Public/cms/template/'.$cmsstyle.'/sitedata/group.xml');
                    $path = getSiteInfo($siteid);
                    $templatePath = '../Public/cms/template/'.$cmsstyle;
                    $dir = opendir($templatePath);
                    @mkdir($path);
                    while(false !== ( $file = readdir($dir)) ) {
                        if (( $file != '.' ) && ( $file != '..' ) && ($file != 'sitedata')) {
                            if ( is_dir($templatePath . '/' . $file) ) {
                                copyTemplateFile($templatePath . '/' . $file,$path . '/' . $file);
                            } else {
                                copy($templatePath . '/' . $file,$path . '/' . $file);
                            }
                        }
                    }
                    closedir($dir);
                }

                $sql_file = YLSNS.'/apps/cms/Appinfo/function';
                if ($handle = opendir($sql_file)) {
                    while (false !== ($file = readdir($handle))) {
                        if ($file != "." && $file != "..") {
                            $type = pathinfo($file, PATHINFO_EXTENSION);
                            $filename = pathinfo($file, PATHINFO_FILENAME);
                            if ($type === 'sql') {
                                $res = file_get_contents($sql_file.'/'.$file);
                                mysql_query('drop function if exists '.$filename.'; DELIMITER //');
                                mysql_query($res);
                            }
                        }
                    }
                    closedir($handle);
                }
			}
		}
		$_SESSION ['installEmail'] = $siteFounder ['email'];
		// 锁定安装
		fopen ( 'install.lock', 'w' );
		@unlink ( '../index.html' );
	} else {
		echo '请重新安装';
	}
	?>
</dd></dl></div>
<p><?php echo $i_message['install_success_intro'];?></p>
<div class="actions">
	<a href="../index.php" class="btn">开始体验 OceanX</a>
</div>
</div>
<?php
}
?>
</div>
	<div class="footer">
		<p>OceanX <?php echo $_YLVERSION; ?> &#169; copyright 2013-<?php echo date('Y') ?> <a target="_blank" href="http://oceanx.yonglang.co">深圳市涌浪网络科技有限公司</a> All Rights Reserved</p>
	</div>
	</div>
</body>
</html>